﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AccCoreLib;
using Giraffe.Core.Common.Messengers;

namespace Giraffe.Core.ICQ
{
    internal class IcqConversationsManager
    {
        private readonly IcqContactsManager _contactsManager;
        private readonly AccSession _userSession;

        private Dictionary<string,IcqConversation> _conversationList = new Dictionary<string, IcqConversation>();
        public event Action<IMessengerContact> NewConversationStarted;

        public IcqConversationsManager(IcqSession userSession, IcqContactsManager contactsManager)
        {
            _contactsManager = contactsManager;
            _userSession = userSession.Session;
            userSession.MessageReceived += OnMessageReceived;
        }

        public IcqConversation GetSingleConversation(IMessengerContact companion)
        {
            if (_conversationList.ContainsKey(companion.ID))
                return _conversationList[companion.ID];

            var newConv = new IcqConversation(companion, _userSession);
            _conversationList[companion.ID] = newConv;
            newConv.Closed += OnConversationClosed;
            return newConv;
        }

        private void OnConversationClosed(IcqConversation conversation)
        {
            _conversationList.Remove(conversation.Companion.ID);
        }

        private void OnMessageReceived(IAccImSession imSession, IAccParticipant companion, IAccIm im)
        {
            bool newConversation = !_conversationList.ContainsKey(companion.user.Name);
            var conversation = GetSingleConversation(_contactsManager[companion.user.Name]);
            var message = new Message(im.Text, (DateTime)im.get_Property(AccImProp.AccImProp_Timestamp),
                                      _contactsManager[companion.user.Name], _contactsManager.OwnContact);
            if (newConversation)
            {
                if (NewConversationStarted != null)
                {
                    NewConversationStarted(_contactsManager[companion.user.Name]);
                }
            }
            conversation.ProcessNewMessage(message);
        }
    }
}
